<template>
  <div>
    <div class="text-right mb-2">
      <el-button @click="getData()" icon="el-icon-refresh" :loading="loading">刷新</el-button>
      <el-button @click="handleView" :disabled="!contractId">查看联保函</el-button>
    </div>

    <table class="table table-bordered table-vertical-middle" v-loading="loading">
      <tr>
        <td width="12%" class="td-label">客户名称</td>
        <td width="38%">{{ relatedData.customer_name }}</td>
        <td width="12%" class="td-label">客户类型</td>
        <td width="38%">{{ relatedData.org_class_name }}</td>
      </tr>
      <tr>
        <td width="12%" class="td-label">贷款金额</td>
        <td width="38%">
          {{ entrustContract.reply_funds || '-' }} 万元 （{{
            entrustContract.reply_funds_capital
          }}）
        </td>
        <td width="12%" class="td-label">贷款期限</td>
        <td width="38%">{{ entrustContract.load_years || '-' }}月</td>
      </tr>
      <tr>
        <td class="td-label">分险比列</td>
        <td colspan="3">
          <div class="text-sm">
            {{ relatedData.bank_name }}: {{ relatedData.bank_risk_rate || '-' }} %
          </div>
          <div class="text-sm">
            {{ relatedData.service_name }}: {{ relatedData.join_risk_rate || '-' }} %
          </div>
          <div class="text-sm">
            {{ relatedData.gua_service_name }}: {{ relatedData.join_risk_rate_qx || '-' }} %
          </div>
        </td>
      </tr>

      <tr>
        <td width="12%" class="td-label">签章日期</td>
        <td width="38%" :class="tdClass">
          <span v-if="viewMode">{{ letter.sign_date }}</span>
          <el-date-picker
            v-else
            v-model="letter.sign_date"
            type="date"
            placeholder="联合担保协议签订时间"
            class="w-100 start-date-pick"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </td>
        <td width="12%" class="td-label"></td>
        <td width="38%"></td>
      </tr>
    </table>

    <div class="text-center py-4" v-if="!viewMode">
      <el-button
        type="primary"
        class="btn-long"
        :loading="submitLoading || loading"
        @click="submit"
      >
        {{ letter.ele_letter_info_id ? '修改' : '添加' }}联保函
      </el-button>
      <!-- <el-button class="btn-long"
                  :loading="submitLoading"></el-button> -->
      <el-button
        type="warning"
        class="btn-long"
        v-if="letter.ele_letter_info_id"
        @click="toSign"
        :loading="submitLoading || loading"
      >
        签章
      </el-button>
    </div>

    <el-dialog
      top="30px"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="beforeClose"
      :visible.sync="letterView"
    >
      <pdf-view :contractId="contractId" :view-mode="true" :query-id="queryId"></pdf-view>
    </el-dialog>
  </div>
</template>

<script>
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
import { nzhToMoney, sub } from '@vimi/utils-tool'
export default {
  components: {
    PdfView,
  },
  props: {
    queryId: String,
    entrustContract: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      loading: false,
      letter: {
        sign_date: '',
      },
      letterView: false,
      submitLoading: false,
      tableName: 'ele_letter_info',
      relatedData: {},
    }
  },
  computed: {
    contractId() {
      return this.letter.doc_id
    },
    viewMode() {
      return +this.letter.sign_status > 0
    },
    tdClass() {
      return this.viewMode ? '' : 'input-td'
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    submit() {
      const guaRate = sub(100, this.relatedData.bank_risk_rate)
      const data = {
        customer_related_id: this.queryId,
        ele_letter_type: 2,
        letter_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd'),
        gua_org_id: this.relatedData.gua_service_id,
        gua_company: this.relatedData.gua_service_name,
        sign_date: this.$utils.dateFormat(this.letter.sign_date, 'yyyy年MM月dd日'),
        customer_name: this.relatedData.customer_name,
        wt_no: this.entrustContract.entrust_contract_cno,
        bank_name: this.entrustContract.bank_name,
        entrust_bank_name: this.entrustContract.entrust_bank_name,
        ensure_contract_no: this.entrustContract.ensure_contract_no,
        loan_contract_no: this.entrustContract.loan_contract_no,
        apply_funds: this.entrustContract.reply_funds,
        apply_funds_capital: nzhToMoney(this.entrustContract.reply_funds * 10000),
        join_date: this.$utils.dateFormat(this.entrustContract.join_date, 'yyyy年MM月dd日'),
        join_no: this.entrustContract.join_no,
        bear_rate_divide: Math.round((this.relatedData.join_risk_rate_qx / guaRate) * 10000) / 100,
        bear_rate: guaRate,
        total_risk_rate: this.relatedData.join_risk_rate_qx,
      }
      if (!this.letter.ele_letter_info_id) {
        this.$api
          .addData(this.$serviceName, this.tableName, data)
          .then(() => {
            this.getData()
            this.$message.success('保存成功!')
          })
          .catch(() => {
            this.$message.error('生成联保函失败')
          })
      } else {
        this.$api
          .updateData(this.$serviceName, this.tableName, this.letter.ele_letter_info_id, {
            ...data,
            // sign_status: 1,
          })
          .then(() => {
            this.getData()
            this.$message.success('更新成功!')
          })
      }
    },
    toSign() {
      this.$api
        .updateData(this.$serviceName, this.tableName, this.letter.ele_letter_info_id, {
          sign_status: 1,
        })
        .then(() => {
          this.getData()
          this.$message.success('签章成功！')
        })
    },
    async getData() {
      this.loading = true
      const params = {
        'ele_letter_type.eq': 2,
        'customer_related_id.eq': this.queryId,
      }
      const res = await this.$api.getData(this.$serviceName, 'customer_related', {
        'customer_related_id.eq': this.queryId,
      })
      this.relatedData = res?.data?.[0] ?? {}
      this.$api
        .getData(this.$serviceName, this.tableName, params, { create_time: 'desc' })
        .then(res => {
          this.letter = res?.data?.[0] ?? { sign_date: '' }
          this.letter.sign_date =
            this.letter?.sign_date?.replace(/(年|月)/g, '-').replace('日', '') ?? ''
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleView() {
      this.letterView = true
    },
    beforeClose() {
      this.letterView = false
    },
  },
}
</script>

<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
.text-sm {
  font-size: 0.875rem;
}
</style>
